import axios from 'axios';
import { getToken, removeToken } from './auth';
import router from '@/router';
import { showNotify } from 'vant';
import { showLoadingToast, closeToast } from 'vant';
import { API_BASE_URL, TIMEOUT } from '@/config.js';

const service = axios.create({
  baseURL: API_BASE_URL,
  timeout: TIMEOUT,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json'
  }
});

// 全局 loading 计数器
let loadingCount = 0;

// 显示全屏 loading
function showFullScreenLoading() {
  if (loadingCount === 0) {
    showLoadingToast({
      message: '加载中...',
      forbidClick: true,
    });
  }
  loadingCount++;
}

// 关闭全屏 loading
function tryHideFullScreenLoading() {
  if (loadingCount <= 0) return;
  loadingCount--;
  if (loadingCount === 0) {
    closeToast();
  }
}

service.interceptors.request.use(
  config => {
    // 请求开始，显示 loading
    showFullScreenLoading();

    const token = getToken();
    if (token) {
      config.headers.Authorization = `${token}`;
    }
    return config;
  },
  error => {
    // 请求失败也关闭 loading
    tryHideFullScreenLoading();
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  res => {
    // 响应回来，先关 loading
    tryHideFullScreenLoading();

    const code = res.data.code;
    const message = res.data.message;
    if (code === 401) {
      removeToken();
      Cookies.remove('username');
      Cookies.remove('userId');
      showNotify({ type: 'warning', message });
      router.push({ path: '/login', query: { redirect: router.currentRoute.value.fullPath } });
      return Promise.reject(new Error('Unauthorized'));
    } else if (code === 500) {
      showNotify({ type: 'danger', message: message || '请求错误' });
      return Promise.reject(res.data);
    } else {
      return Promise.resolve(res.data);
    }
  },
  error => {
    // 网络错误也关 loading
    tryHideFullScreenLoading();
    showNotify({ type: 'danger', message: error.message || '网络错误' });
    return Promise.reject(error);
  }
);

export default service;
